package cn.fsw.pethome.base.controller;

import cn.fsw.pethome.util.AjaxResult;
import cn.fsw.pethome.util.FastdfsUtil;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;

import java.io.IOException;

@RestController
@RequestMapping("/fastDFS")
public class FastDFSController {

    @PostMapping("/upload")
    public AjaxResult upload(@RequestPart(required = true,value = "file")MultipartFile file){
        if (file == null){
            return AjaxResult.error().setMsg("文件不能为空");
        }
        try {
            //获取字节
            byte[] bytes = file.getBytes();
            //获取名字
            String originalFilename = file.getOriginalFilename();
            //用.分割,获取最后一个.的位置
            int i = originalFilename.lastIndexOf(".");
            //后缀名
            String substring = originalFilename.substring(i + 1);
            //完整的路径
            String upload = FastdfsUtil.upload(bytes,substring);
            return AjaxResult.ajaxResult().setData(upload);
        } catch (IOException e) {
            e.printStackTrace();
            return AjaxResult.error().setMsg("网络异常");
        }
    }

    @DeleteMapping
    public AjaxResult delete(@RequestParam(required = true,value = "path") String  path){
        try {
            String pathTmp = path.substring(1); // goup1/xxxxx/yyyy
            String groupName =  pathTmp.substring(0, pathTmp.indexOf("/")); //goup1
            String remotePath = pathTmp.substring(pathTmp.indexOf("/")+1);// /xxxxx/yyyy
            FastdfsUtil.delete(groupName,remotePath);
            return AjaxResult.ajaxResult();
        } catch (Exception e) {
            e.printStackTrace();
            return AjaxResult.error().setMsg("网络异常");
        }
    }
}
